package com.xc.quickstart.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.xc.quickstart.admin.query.SSOQuery;
import com.xc.quickstart.common.annotation.PassToken;
import com.xc.quickstart.common.context.ApiContext;
import com.xc.quickstart.common.model.ApiContextModel;
import com.xc.quickstart.common.model.ApiResponse;
import com.xc.quickstart.manager.sso.SsoManager;
import com.xc.sso.model.dto.TokenUser;
import com.xc.sso.util.UserTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

@Slf4j
@Component
public class AdminTokenInterceptor extends HandlerInterceptorAdapter {

    private static final String XCTOKEN = "tctoken";
    private static final String MERCHANT = "xcmchid";

    @Autowired
    private SsoManager ssoManager;
    @Value("${sso.admin_app_id}")
    private String apiAppId;

    private static final Set<String> METHOD_NAME_WHITE_SET = new HashSet<>();

    static {
        METHOD_NAME_WHITE_SET.add("uploadImg");
        METHOD_NAME_WHITE_SET.add("uploadWatermarkImg");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if (!judge(handler)) {
            return true;
        }


        String token = request.getHeader(XCTOKEN);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        if (StringUtils.isBlank(token)) {
            response.getWriter().print(JSON.toJSONString(ApiResponse.INVALID_TOKEN));
        }

        if (!ssoManager.checkToken(new SSOQuery(token, apiAppId))) {
            response.getWriter().print(JSON.toJSONString(ApiResponse.INVALID_TOKEN));
        }

        TokenUser tokenUser = UserTokenUtil.getUserByToken(token);

        ApiContextModel apiContextModel = ApiContext.getApiContextModel();
        apiContextModel.setUserId(tokenUser.getUserId().intValue());
        apiContextModel.setJobNumber(tokenUser.getJobnumber());
        apiContextModel.setUserName(tokenUser.getName());

        String mchId = request.getHeader(MERCHANT);
        apiContextModel.setXcmchid(StringUtils.isNumeric(mchId) ? Integer.parseInt(mchId) : 0);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ApiContext.removeApiContextModel();
    }

    private boolean judge(Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return false;
        }

        Method method = ((HandlerMethod) handler).getMethod();
        Class<?> declaringClass = method.getDeclaringClass();

        PassToken annotation = method.getAnnotation(PassToken.class);
        if (Objects.isNull(annotation)) {
            annotation = declaringClass.getAnnotation(PassToken.class);
        }

        if (Objects.nonNull(annotation)) {
            return false;
        }

        return true;
    }

}
